<template>
  <view class="time-picker-popup" v-if="show">
    <!-- 遮罩层 -->
    <view class="mask" @click="close"></view>

    <!-- 弹窗内容 -->
    <view class="popup-content">
      <!-- 标题栏 -->
      <view class="title">
        <view class="utitle">请选择配送时间</view>
        <view class="close" @click="close">
          <text class="icon-close">✖</text>
        </view>
      </view>

      <!-- 内容区域 -->
      <view class="content">
        <!-- 日期选择区域 -->
        <view class="left">
          <block v-for="(day, index) in dateList" :key="index">
            <view
              class="l_item"
              :class="{ active: activeDate === index }"
              @click="selectDate(index)"
            >
              {{ day.label }}
            </view>
          </block>
        </view>

        <!-- 时间选择区域 -->
        <view class="right">
          <scroll-view
            scroll-y="true"
            class="scroll-Y"
            :scroll-into-view="'one' + activeIndex"
          >
            <block v-for="(item, index) in selection" :key="index">
              <view
                class="r_item"
                :class="{ active: item.active, disabled: item.disabled }"
                @click="!item.disabled && selectTime(item)"
                :id="'one' + (index + 1)"
              >
                {{ item.time }}
                <text v-if="item.active" class="check-icon">✔</text>
              </view>
            </block>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "TimePickerPopup",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "选择预约时间",
    },
    times: {
      type: Array,
      default: () => ["00:00", "00:15", "00:30", "00:45", "23:59"],
    },
    defaultTime: {
      type: String,
      default: "立即配送",
    },
  },
  data() {
    return {
      show: false,
      dateList: [], // 日期列表（今天 + 未来7天）
      selection: [], // 时间列表
      activeDate: 0, // 当前选中的日期索引
      activeIndex: 0, // 滚动定位的初始值
    };
  },
  watch: {
    visible(newVal) {
      this.show = newVal; // 更新组件显示状态
      if (newVal) this.initialize(); // 如果弹窗显示，初始化数据
    },
  },
  methods: {
    initialize() {
      this.generateDates(); // 生成日期列表
      this.getTimeList(); // 获取时间列表
    },
    close() {
      this.show = false;
      this.$emit("update:visible", false); // 通知父组件关闭弹窗
    },
    selectDate(index) {
      this.activeDate = index; // 更新当前选择的日期
      this.getTimeList(); // 根据日期重新获取时间列表
    },
    selectTime(item) {
      // 设置选中的时间
      this.selection.forEach((time) => (time.active = false));
      item.active = true;

      // 触发选择事件
      this.$emit("onSelect", {
        date: this.dateList[this.activeDate]?.date,
        time: item.time,
      });

      this.close(); // 关闭弹窗
    },
    generateDates() {
      const weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      this.dateList = [];

      for (let i = 0; i < 8; i++) {
        const now = new Date();
        now.setDate(now.getDate() + i); // 计算未来日期
        const yy = now.getFullYear();
        const mm = String(now.getMonth() + 1).padStart(2, "0");
        const dd = String(now.getDate()).padStart(2, "0");
        const wk = weeks[now.getDay()];

        this.dateList.push({
          label: i === 0 ? `今天(${wk})` : `${mm}-${dd}(${wk})`,
          date: `${yy}-${mm}-${dd}`,
        });
      }
    },
    getTimeList() {
      const isToday = this.activeDate === 0; // 是否选择今天
      const now = new Date();
      const currentTime = `${String(now.getHours()).padStart(2, "0")}:${String(
        now.getMinutes()
      ).padStart(2, "0")}`;

      const times = [];
      for (let hour = 0; hour < 24; hour++) {
        const start1 = `${String(hour).padStart(2, "0")}:00`;
        const end1 = `${String(hour).padStart(2, "0")}:30`;
        times.push(`${start1} - ${end1}`);

        const start2 = `${String(hour).padStart(2, "0")}:30`;
        const end2 = `${String(hour + 1).padStart(2, "0")}:00`;
        times.push(`${start2} - ${end2}`);
      }

      this.selection = times.map((time) => {
        const [start] = time.split(" - ");
        return {
          time,
          active: this.defaultTime === time,
          disabled: isToday && currentTime > start, // 禁用今天已过时间
        };
      });

      this.selection.unshift({
        time: "立即配送",
        active: this.defaultTime === "立即配送",
        disabled: false,
      });

      this.activeIndex = this.selection.findIndex((item) => item.active) + 1;
    },
  },
};
</script>


<style lang="scss" scoped>
	.left {
		width: 35%;
		background-color: #f6f6f6;

		.l_item {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			font-size: 32rpx;
			border-bottom: 1px solid #e5e5e5;

			&.active {
				color: #42c8b4;
				font-weight: bold;
			}
		}
	}

	.time-picker-popup {

		/* 遮罩层 */
		.mask {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
			z-index: 999;
		}

		/* 弹窗主体 */
		.popup-content {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			background-color: #fff;
			border-top-left-radius: 10px;
			border-top-right-radius: 10px;
			z-index: 1000;
			// padding: 20rpx;

			.title {
				display: flex;
				justify-content: center;
				align-items: center;
				position: relative;
				font-size: 36rpx;

				.close {
					position: absolute;
					right: 20rpx;
					font-size: 40rpx;
					color: #aaa;
				}
			}

			.content {
				display: flex;
				height: 570rpx;

				.left {
					width: 30%;
					text-align: center;
					background-color: #f6f6f6;
					height: 100%;

					.l_item {
						height: 80rpx;
						line-height: 80rpx;
					}
				}

				.right {
					width: 70%;
					height: 100%;
					// padding-left: 10rpx;

					.scroll-Y {
						height: 420rpx;
						/* 设置固定高度，使时间列表区域可滚动 */
						overflow-y: scroll;
						height: 100%;
						/* 允许滚动 */
					}

					.r_item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						height: 80rpx;
						border-bottom: 1px solid #f1f1f1;
						font-size: 32rpx;
						padding-left: 40rpx;

						&.active {
							color: #42c8b4;
						}

						&.disabled {
							color: #ccc;
						}
					}
				}
			}

			.check-icon {
				color: #42c8b4;
				font-size: 36rpx;
			}
		}
	}
</style>